import { Button, Card, Popconfirm, Statistic, Table, Tag, message } from 'antd';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { dropCourse, getMyCourses } from '../../api/student';
import { Course } from '../../types';

export default function Selected() {
  const qc = useQueryClient();
  const { data: list = [], isLoading } = useQuery({ queryKey: ['me', 'courses'], queryFn: getMyCourses });

  const credit = list.reduce((s, c) => s + (c.credit || 0), 0);

  const mutation = useMutation({
    mutationFn: (courseId: string) => dropCourse(courseId),
    onSuccess: async () => {
      message.success('已退选');
      await Promise.all([
        qc.invalidateQueries({ queryKey: ['me', 'courses'] }),
        qc.invalidateQueries({ queryKey: ['courses', 'approved'] }),
      ]);
    },
  });

  return (
    <div className="space-y-4">
      <div className="grid md:grid-cols-2 gap-4">
        <Card><Statistic title="已选课程" value={list.length} suffix="门" /></Card>
        <Card><Statistic title="已选学分" value={credit} suffix="学分" /></Card>
      </div>
      <Card>
        <Table<Course>
          loading={isLoading}
          rowKey="id"
          dataSource={list}
          columns={[
            { title: '课程名称', dataIndex: 'name' },
            { title: '任课教师', dataIndex: 'teacherName' },
            {
              title: '上课时间',
              render: (_, c) => (
                <>
                  {c.timeSlots.map((t, i) => (
                    <Tag key={i}>{`周${t.dayOfWeek} ${t.start}-${t.end}`}</Tag>
                  ))}
                  {(() => {
                    const { startWeek, endWeek } = getWeekRange(c);
                    return (
                      <Tag color="blue">{startWeek && endWeek ? `第${startWeek}-${endWeek}周` : '周次待定'}</Tag>
                    );
                  })()}
                </>
              ),
            },
            { title: '学分', dataIndex: 'credit' },
            { title: '选课人数', render: (_, c) => `${c.enrolledCount}/${c.capacity}` },
            {
              title: '操作',
              render: (_, c) => (
                <Popconfirm title="确认退选该课程？" onConfirm={() => mutation.mutate(c.id)}>
                  <Button danger>退课</Button>
                </Popconfirm>
              ),
            },
          ]}
          pagination={false}
        />
      </Card>
    </div>
  );
}

function getWeekRange(course: Course): { startWeek?: number; endWeek?: number } {
  let minStart: number | undefined;
  let maxEnd: number | undefined;
  for (const s of course.timeSlots) {
    if (s.weeks && s.weeks.length) {
      const wmin = Math.min(...s.weeks);
      const wmax = Math.max(...s.weeks);
      minStart = minStart === undefined ? wmin : Math.min(minStart, wmin);
      maxEnd = maxEnd === undefined ? wmax : Math.max(maxEnd, wmax);
    }
    if (s.startWeek !== undefined) {
      minStart = minStart === undefined ? s.startWeek : Math.min(minStart, s.startWeek);
    }
    if (s.endWeek !== undefined) {
      maxEnd = maxEnd === undefined ? s.endWeek : Math.max(maxEnd, s.endWeek);
    }
  }
  return { startWeek: minStart, endWeek: maxEnd };
}


